<template>
  <Dialog class="issued-dialog" v-model="visiable" :title="formTitle" style="max-width: 1000px;" width="70%" @submit="onSubmit">
    <el-segmented class="menu" v-model="currTime" :options="dutyTimeList" />
    <el-form class="table-form" :model="formData" ref="formRef" label-suffix="：">
      <el-table :data="formData.tableData" :span-method="tableSpanMethod" :max-height="540" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="group" label="分组" width="200">
          <template #default="{ row, $index }">
            <section class="table-form-row-group">
              <p><em>{{ row.mc }}</em>({{ row.dd }})</p>
              <el-button link type="primary" :icon="Plus" @click="onAddChild(row, $index)">添加子项</el-button>
            </section>
          </template>
        </el-table-column>
        <el-table-column label="下发单位" width="200">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData.${$index}.xfdw`">
              <el-select v-model="row.dw" placeholder="请选择下发单位">
                <el-option v-for="item in PCS_MAP" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="上报人数" width="160">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData.${$index}.sbrs`">
              <el-input-number v-model="row.sbrs" :min="1">
                <template #suffix>人</template>
              </el-input-number>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData.${$index}.bz`">
              <el-input v-model="row.bz" type="textarea" :rows="1" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="{ row, $index }">
            <el-popconfirm title="确认删除吗？" :hide-after="0" @confirm="onDelete($index)">
              <template #reference>
                <el-button :disabled="!row.isChild" link :type="row.isChild ? 'danger' : ''">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </Dialog>
</template>

<script setup>
import { computed, ref, reactive } from 'vue';
import { SECURITY_STATUS } from '@/views/SystemSetting/config'
import { issuedApi } from '@/api/DutyManage'
import { PCS_MAP } from '@/config'
import { Plus } from '@element-plus/icons-vue'
import { uniqueId } from 'lodash'

const emits = defineEmits(['submited']);
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
});

const visiable = ref(false);
const formType = ref('add'); // add, edit
const formTitle = computed(() => `${formType.value === 'add' ? '下发' : '编辑'}${props.name}`);

const currTime = ref('');
const dutyTimeList = ref([]);

const formData = reactive({ tableData: [] });
const formRules = {
  bh: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  mc: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  zt: [{ required: true, message: '请选择状态', trigger: 'blur' }],
}

const initFormData = (type, row) => {
  // if (type == 'add') formData = { zt: SECURITY_STATUS['启用'] };
  // if (type == 'edit') formData = { ...row };
}

const show = (type = 'add', row = null) => {
  formType.value = type;
  initFormData(type, row);
  getDutyTimeList();
  getDutyGroupList();
  visiable.value = true;
};

const onAddChild = (row, index) => {
  console.log('row', row, index);
  formData.tableData.splice(index + 1, 0, { ...row, isChild: true, id: uniqueId(`${row.mc}_`), xfdw: '', sbrs: 1, bz: '' });
}

const onDelete = index => {
  formData.tableData.splice(index, 1);
}

const tableSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property === 'group') {
    if (row.isChild) return { rowspan: 0, colspan: 0 };
    let count = 0;
    for (let i = rowIndex + 1; i < formData.tableData.length; i++) {
      if (formData.tableData[i].isChild) count++;
      else break;
    }
    return { rowspan: count + 1, colspan: 1 };
  }
}

const onSubmit = () => {
  setTimeout(() => {
    visiable.value = false;
    emits('submited')
  }, 2000);
}

const getDutyTimeList = async () => {
  try {
    const res = await issuedApi.timeList({});
    dutyTimeList.value = res.data;
    currTime.value = res.data[0];
  } catch (error) {
    console.error(error);
  }
}

const getDutyGroupList = async () => {
  try {
    const res = await issuedApi.groupList({});
    formData.tableData = res.data.map(item => ({
      ...item,
      sbrs: 1,
    }))
  } catch (error) {
    console.error(error);
  }
}

defineExpose({ show });
</script>

<style lang="scss" scoped>
.menu {
  border-radius: var(--el-border-radius-base);

  &.el-segmented {
    :deep(.el-segmented__item) {
      user-select: none;
      font-size: var(--el-font-size-base);
      padding: 4px 8px;
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }

    :deep(.el-segmented__item-label) {
      overflow: unset;
    }

    // :deep(.el-segmented__item-selected) {
    //   box-shadow: var(--ycy-box-shadow-primary);
    // }
  }
}

.table-form {
  margin-top: var(--ycy-gap-large);
  // padding: 16px;
  // background-color: var(--el-fill-color-light);
  // overflow: hidden;
  // border-radius: var(--el-border-radius-base);
  // border: 1px solid var(--el-border-color);

  .table-form-row-group {
    em {
      margin-right: calc(var(--ycy-gap-small) / 2);
      font-style: normal;
      font-weight: bold;
      // color: var(--el-color-primary);
    }

    .el-button {
      padding: 0;
      font-size: 12px;
      height: unset;
    }
  }
}
</style>